<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script type="text/javascript" src="js/json2.js"></script>
    <script type="text/javascript">
        function method01(){
            //获取网页中需要传送的数据
            var usernamevalue=document.getElementById('username').value;
            var userpasswordvalue=document.getElementById('userpassword').value;
            //把数据封装到js对象里
            var jsObject=new Object();
            jsObject.name = usernamevalue;
            jsObject.password=userpasswordvalue;
            //把js对象转换成json格式字符串
            var jsonString=JSON.stringify(jsObject);
            console.log('传送的json格式字符串为：'+jsonString+'。');


            var xhr=new  XMLHttpRequest();
            xhr.open('POST','/xxxx/servlet/servlet01');
            //告诉服务器端  数据的组织方式是json
            xhr.setRequestHeader('Content-Type','application/json');
            xhr.onreadystatechange=function(){
                if(xhr.readyState==4){
                    if(xhr.status==200){
                        //返回的是json格式字符串
                        var backContet=xhr.responseText;
                        console.log('后台返回的内容为：'+backContet+'。');
                        //把json格式字符串转换成json对象
                        var jsonObjectBack=eval('('+backContet+')');


                        var usernamespan=document.getElementById('usernameback');
                        var userpasswordspan=document.getElementById('userpasswordback');
                        usernamespan.innerHTML=jsonObjectBack.name;
                        userpasswordspan.innerHTML=jsonObjectBack.password;

                    }

                }
            }
            xhr.send(jsonString);





        }

    </script>

</head>
<body>
用户名：<input type="text" id="username"><br>
密码：<input type="password" id="userpassword"><br>
<input type="button" value="提交" onclick="method01()">
<input type="button" value=重置>
<hr>
返回的数据：<br>
用户名：<span id="usernameback"></span><br>
密码：<span id="userpasswordback"></span><br>




</body>
</html>